<?php

class Cache extends Engine {
    static public $CACHE_FILE = '';
    static public $CACHE_PATH = '';

    public static function init() {
        $page = (get('page') != '') ? get('page') : 'index';

        self::$CACHE_PATH = CACHE_PATH . $page . DS;

        $action = 'default';
        if (post('action')) {
            $action = post('action');
        } elseif (get('action')) {
            $action = get('action');
        }

        self::$CACHE_FILE = md5($action . $_SERVER['REQUEST_URI']);

        self::get(false);

        return true;

    }

    public static function get($toReturn = true) {
        if (self::exists()) {
            $cacheTime = time() - filemtime (self::$CACHE_PATH . self::$CACHE_FILE);
            if ($cacheTime > CACHE_TIME) {
                unlink(self::$CACHE_PATH . self::$CACHE_FILE);
                return false;
            }
            if ($toReturn) {
                return file_get_contents(self::$CACHE_PATH . self::$CACHE_FILE);
            }
            print file_get_contents(self::$CACHE_PATH . self::$CACHE_FILE); die;
        }

        return false;
    }

    public static function set($output) {
        $cacheReady = true;
        if (!is_dir(self::$CACHE_PATH)) {
            $cacheReady = false;
            if (mkdir(self::$CACHE_PATH, 0700, true)) {
                $cacheReady = true;
            }
        }

        if (!$cacheReady) return false;

        file_put_contents(self::$CACHE_PATH . self::$CACHE_FILE, $output);
        return true;
    }

    public static function exists() {
        return file_exists(self::$CACHE_PATH . self::$CACHE_FILE);
    }

    public static function removeByGroup($groupKey) {
        $cgId = self::$DB->selectCell("SELECT id FROM ?f WHERE cg_key = ?", TAB_CACHE_GROUPS, $groupKey);

        $r = self::$DB->q("SELECT p_url FROM ?f WHERE p_cache_group_id = ?i", TAB_PAGES, $cgId);

        $urls = array();
        while ($url = $r->fetch_array()) {

            if (is_dir(CACHE_PATH . $url['p_url'] . DS)) {
                Utils::rRmDir(CACHE_PATH . $url['p_url'] . DS);
            }
        }
    }

    public static function clean() {
        if (is_dir(CACHE_PATH)) {
            Utils::rRmDir(CACHE_PATH);
        }
    }
}
